var express = require("express");
var router = express.Router();
let article = require("../model/article")
let resource = require("../model/resource")
let problem = require("../model/problem")

router.post("/api/v1/searchData", async (req, res) => {
  console.log(req.body);
  let queryInput = req.body.input
  let type = req.body.type
  let sort = req.body.sort
  let searchData = []
  let articleData = []
  let resourceData = []
  let problemData = []
  console.log(type)
  switch (type) {
    case "珠海港圈":
      articleData = await article.find({
        articlename: queryInput,
        aeticletype: "珠海港圈"
      }).populate({path: 'userid', populate: {path: 'department'}})
      searchData = articleData
      
      break;
    case "创新建议":
      articleData = await article.find({
        articlename: queryInput,
        aeticletype: "创新建议"
      }).populate({path: 'userid', populate: {path: 'department'}})
      searchData = articleData
      break;
    case "资源共享":
      resourceData = await resource.find({
        resourcename: queryInput
      }).populate({path: 'userid', populate: {path: 'department'}})
      searchData = resourceData
      break;
    case "互帮互助":
      problemData = await problem.find({
        problemname: queryInput
      }).populate([{path:"userid"}, {path:"adopt",populate: {path: 'userid', populate: {path: 'department'}}}])
      searchData = problemData
      break;

    default:
      articleData = await article.find({
        articlename: queryInput
      })
      resourceData = await resource.find({
        resourcename: queryInput
      })
      problemData = await problem.find({
        problemname: queryInput
      })
      searchData = articleData.concat(resourceData, problemData)
      break;
  }

  if (sort == "最新发布") {
    searchData.sort((a, b) => {
      return Date.parse(b.release_time) - Date.parse(a.release_time)
    })
  } else {
    searchData.sort((a, b) => {
      return b.reading - a.reading
    })
  }
  res.json({
    code: 200,
    data: searchData
  });
})

// 导出模块（在 app.js 中引入）
module.exports = router;